//
//  ViewController.swift
//  movieInfo
//
//  Created by zhangkai on 2023/5/7.
//

import UIKit
import SDCycleScrollView
import GoogleMobileAds
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate{
    
    private var rewardedAd: GADRewardedAd?
    
    
    
    func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didSelectItemAt index: Int) {
        
        
        let vc = ViewControllerInfoVC()
        vc.model = self.headS[index]
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    var tableView:UITableView!
    var data = ["Now Playing","Actors","Upcoming","Top Rated","Popular"]
    
    var showView = TodayShowView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
//
    
    
//    var tmh:
//    var：

    var maxInt = 0
    
    var one:[Movie] = []
    var two:[Cast] = []
    var three:[Movie] = []
    var four:[Movie] = []
    var five:[Movie] = []
    
    var headView:SDCycleScrollView!
    var headS:[Movie] = []
    

    @objc func magnifyingglass(){
        
        let vc = searchViewVC()
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)

        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        
        
        let str = UserDefaults.standard.object(forKey: "isVIP") as? String ?? ""
        if str == "1"{
            
        }else{
//            self.showAD()
        }
        
        
//
        self.view.backgroundColor = .white
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "magnifyingglass"), style: .plain, target: self, action: #selector(magnifyingglass))
        

        headView = SDCycleScrollView()
        headView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 180)
        headView.bannerImageViewContentMode = .scaleAspectFill
        headView.delegate = self
        
        
        

        
        tableView = UITableView(frame: CGRectZero, style: .grouped)
        tableView.register(ViewControllerCell.self, forCellReuseIdentifier: "ViewControllerCell")
        tableView.register(TableViewPersonCell.self, forCellReuseIdentifier: "TableViewPersonCell")
        tableView.backgroundColor = .secondarySystemBackground
//        tableView.rowHeight = 54
        tableView.estimatedSectionFooterHeight = 0.01
        tableView.estimatedSectionHeaderHeight = 44
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        tableView.tableHeaderView = headView
        
        getData()
        
        
     
        
        
        
        

    }
    
    @objc func dismissView(){
        showView.removeFromSuperview()
    }
    
    func showTipView(){
        
        return
        if self.maxInt == 4{
            
            DispatchQueue.main.async {
                var allrr:[Movie] = []
                allrr.append(contentsOf: self.one)
                allrr.append(contentsOf: self.three)
                allrr.append(contentsOf: self.four)
                allrr.append(contentsOf: self.five)
                let model = allrr.randomElement()
                
                self.showView.model = model
                self.showView.allModel = allrr
                self.view.addSubview(self.showView)
                self.showView.isUserInteractionEnabled = true
                let tap = UITapGestureRecognizer(target: self, action: #selector(self.dismissView))
                self.showView.addGestureRecognizer(tap)
                self.showView.backgroundColor = UIColor.darkGray.withAlphaComponent(0.2)
                
            }
            
        }
        
       
        
        
    }
    
    
    func getData(){
        
        
        let url = MMNetWork.shared.getMoviesURL(endpoint: .topRated, page: 1)
        MMNetWork.shared.fetchData(urlString: url, castType: [Movie].self, keyPath: "results") { result in
            switch result {
            case .success(let movies):
//                completed(.success(movies))
                self.one =  movies.shuffled()
                DispatchQueue.main.async {
                    self.maxInt = self.maxInt + 1
                    self.tableView.reloadData()
                    self.showTipView()
                }
              
                break
            case .failure(let error):
                self.maxInt = self.maxInt + 1
                self.showTipView()
                break
            }
        }
//
        
        let twourl = MMNetWork.shared.getNewPersonURL(ID: "", page: 1)
        
        MMNetWork.shared.fetchData(urlString: twourl, castType: [Cast].self, keyPath: "results") { result in
            switch result {
            case .success(let movies):
//                completed(.success(movies))
                self.two = movies.shuffled()
//                self.tableView.reloadData()
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
                
                break
            case .failure(let error):
//                completed(.failure(error))
                break
            }
        }
        
        let url1 = MMNetWork.shared.getMoviesURL(endpoint: .nowPlaying, page: 1)
        MMNetWork.shared.fetchData(urlString: url1, castType: [Movie].self, keyPath: "results") { result in
            switch result {
            case .success(let movies):
//                completed(.success(movies))
                self.three = movies.shuffled()
                DispatchQueue.main.async {
                    self.maxInt = self.maxInt + 1
                    self.tableView.reloadData()
                    self.showTipView()
                }
               
                break
            case .failure(let error):
                self.maxInt = self.maxInt + 1
                self.showTipView()
                break
            }
        }
        
        let url2 = MMNetWork.shared.getMoviesURL(endpoint: .upcoming, page: 1)
        MMNetWork.shared.fetchData(urlString: url2, castType: [Movie].self, keyPath: "results") { result in
            switch result {
            case .success(let movies):
//                completed(.success(movies))
                self.four = movies.shuffled()
                DispatchQueue.main.async {
                    self.maxInt = self.maxInt + 1
                    self.tableView.reloadData()
                    self.showTipView()
                }
              
                break
            case .failure(let error):
                self.maxInt = self.maxInt + 1
                self.showTipView()
                break
            }
        }
        
        let url3 = MMNetWork.shared.getMoviesURL(endpoint: .popular, page: 1)
        MMNetWork.shared.fetchData(urlString: url3, castType: [Movie].self, keyPath: "results") { result in
            switch result {
            case .success(let movies):
//                completed(.success(movies))
                self.five = movies.shuffled()
                
                var urls:[String] = []
                self.headS = []
                for i in 0..<movies.count{
                    let model = movies[i]
                    if i < 6{
                        
                let url = "https://image.tmdb.org/t/p/w500\(model.posterPath ?? "")"
                urls.append(url)
      
                        self.headS.append(model)
                    }
                    
                    
                }
                
                
                DispatchQueue.main.async {
                    self.maxInt = self.maxInt + 1
                    self.headView.imageURLStringsGroup = urls
                    self.tableView.reloadData()
                    self.showTipView()
                }
               
                break
            case .failure(let error):
                self.maxInt = self.maxInt + 1
                self.showTipView()
                break
            }
        }

        
        
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 5
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return 1
        
       
   }
   
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        if indexPath.section == 1{
            let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewPersonCell", for: indexPath) as? TableViewPersonCell ?? TableViewPersonCell()

            cell.selectionStyle = UITableViewCell.SelectionStyle.none
            cell.configData(datas: self.two)
            cell.callBlock = { [weak self] model in
                let vc = PersonInfoViewVC()
                vc.id = model.id
//                personinfo
                self?.navigationController?.pushViewController(vc, animated: true)
//
                
            }
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "ViewControllerCell", for: indexPath) as? ViewControllerCell ?? ViewControllerCell()

            cell.textLabel?.textColor = UIColor.black
            cell.backgroundColor = .clear
            cell.selectionStyle = UITableViewCell.SelectionStyle.none
            
            
            if indexPath.section == 0{
                cell.configData(datas: self.one)
            }else if indexPath.section == 2{
                cell.configData(datas: self.three)
            }else if indexPath.section == 3{
                cell.configData(datas: self.four)
            }else if indexPath.section == 4{
                cell.configData(datas: self.five)
            }
            
            
            cell.callBlock = { [weak self] model in
                
                if indexPath.section == 0{
                    print("1")
                    let vc = ViewControllerInfoVC()
                    vc.model = model
                    vc.hidesBottomBarWhenPushed = true
                    self?.navigationController?.pushViewController(vc, animated: true)
                }else if indexPath.section == 2{
                    print("2")
                    let vc = ViewControllerInfoVC()
                    vc.model = model
                    vc.hidesBottomBarWhenPushed = true
                    self?.navigationController?.pushViewController(vc, animated: true)
                }else if indexPath.section == 3{
                    print("3")
                    let vc = ViewControllerInfoVC()
                    vc.model = model
                    vc.hidesBottomBarWhenPushed = true
                    self?.navigationController?.pushViewController(vc, animated: true)
                }else if indexPath.section == 4{
                    print("4")
                    let vc = ViewControllerInfoVC()
                    vc.model = model
                    vc.hidesBottomBarWhenPushed = true
                    self?.navigationController?.pushViewController(vc, animated: true)
                }
                
                
                
            }
            
            
            return cell
        }
   }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 1{
            
          
            return 90
        }else{
            return 240
        }
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let curView = UIView()
        curView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44)
        curView.backgroundColor = .white
        
        let lebael = UILabel()
        lebael.font = UIFont.systemFont(ofSize: 18, weight: .bold)
        lebael.textColor = .black
        lebael.text = data[section]
        curView.addSubview(lebael)
        lebael.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(15)
        }
        
        let btn = UIButton()
        btn.tag = section
        btn.tag = section
        btn.setTitle("See more >", for: .normal)
        btn.setTitleColor(UIColor(red: 0.15, green: 0.2, blue: 0.25, alpha: 1), for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        curView.addSubview(btn)
        btn.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-15)
        }
        btn.addTarget(self, action: #selector(click(sender:)), for: .touchDown)
        if section == 1{
            btn.isHidden = true
        }else{
            btn.isHidden = false
        }
        
        return curView
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44
    }
    

    
    @objc func click(sender:UIButton){
        
        let vc = AllMovieVc()
        if sender.tag == 0{
            vc.type = .topRated
        }else if sender.tag == 1{
            
        }else if sender.tag == 2{
            vc.type = .nowPlaying
            
        }else if sender.tag == 3{
            vc.type = .upcoming
            
        }else if sender.tag == 4{
            vc.type = .popular
            
        }
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
        
        
    }
    
    
    
    
    func showAD(){
        

        
//        ca-app-pub-3940256099942544/1712485313
//pub-3940256099942544/1712485313
//        ca-app-pub-5223367835995553/7835846466

//        ca-app-pub-5223367835995553/7835846466 正式

        let request = GAMRequest()
        GADRewardedAd.load(withAdUnitID:"ca-app-pub-5223367835995553/7835846466",
                           request: request,
                           completionHandler: { [self] ad, error in
            
//            self.isBool = false
            
          if let error = error {
            print("Failed to load rewarded ad with error: \(error.localizedDescription)")
              
            return
          }
          rewardedAd = ad
            rewardedAd?.present(fromRootViewController: self, userDidEarnRewardHandler: { [weak self] in
//                self?.isBool = true
   
            })
//            rewardedAd?.fullScreenContentDelegate = self
          print("Rewarded ad loaded.")
        }
        )
        
        
    }
    
  
}




